package com.webank.wedatasphere.qualitis.util;

import com.webank.wedatasphere.qualitis.project.entity.Project;
import com.webank.wedatasphere.qualitis.response.RuleDetailDTO;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;

public class WordUtil {
    public static void exportWord(HttpServletRequest request, HttpServletResponse response, String content, String fileName) throws Exception {
        //这里是必须要设置编码的，不然导出中文就会乱码。
        byte[] b = content.getBytes("GBK");
        //将字节数组包装到流中
        ByteArrayInputStream bais = new ByteArrayInputStream(b);
        POIFSFileSystem poifs = new POIFSFileSystem();
        DirectoryEntry directory = poifs.getRoot();
        //该步骤不可省略，否则会出现乱码。
        DocumentEntry documentEntry = directory.createDocument("WordDocument", bais);
        //输出文件
        request.setCharacterEncoding("utf-8");
        //导出word格式
        response.setContentType("application/msword");
        response.addHeader("Content-Disposition", "attachment;filename=" +
                new String(fileName.getBytes("GB2312"), "iso8859-1") + ".doc");
        ServletOutputStream ostream = response.getOutputStream();
        poifs.writeFilesystem(ostream);
        bais.close();
        ostream.close();
        poifs.close();
    }

    public static XWPFDocument generateWordXWPFDocument(Project project, List<RuleDetailDTO> ruleDetailDTOS, Map<String, Object> map) {
        XWPFDocument doc = new XWPFDocument();
        // Title
        createTitle(doc, "数据质量分析报告");
        createParagraph(doc, "");
        String row1 = "数据质量标准名称：" + project.getCnName() + "\t 版本号：1.1";
        String row2 = "执行开始时间：" + map.get("beginTime") + "\t 执行结束时间：" + map.get("endTime");
        String row3 = "参考文献：" + project.getCkwx() + "\t 数据质量标准类型：" + project.getSjzllx();
        String row4 = "执行规则总数：" + map.get("ruleTotal") + "\t 执行通过：1.1" + map.get("ruleSuccess");
        String row5 = "执行未通过：" + map.get("ruleFail");
        createParagraph(doc, row1);
        createParagraph(doc, "");
        createParagraph(doc, row2);
        createParagraph(doc, "");
        createParagraph(doc, row3);
        createParagraph(doc, "");
        createParagraph(doc, row4);
        createParagraph(doc, "");
        createParagraph(doc, row5);
        for (RuleDetailDTO ruleDetailDTO : ruleDetailDTOS) {
            createParagraph(doc, "");
            createParagraph(doc, ruleDetailDTO.getRuleType());
            String varT1 = "执行引擎：" + ruleDetailDTO.getDataSourceEngine()
                    + "\t 数据库名：" + ruleDetailDTO.getDatabaseName()
                    + "\t 数据表名：" + ruleDetailDTO.getTableName();
            createParagraph(doc, "");
            createParagraph(doc, varT1);
            XWPFParagraph paragraph = doc.createParagraph();
            XWPFTable table = paragraph.getDocument().createTable(2, 5);
            table.setWidth(500);
            table.setCellMargins(20, 20, 20, 20);
            //表格属性
            CTTblPr tablePr = table.getCTTbl().addNewTblPr();
            //表格宽度
            CTTblWidth width = tablePr.addNewTblW();
            width.setW(BigInteger.valueOf(8000));
            List<XWPFTableCell> tableCells = table.getRow(0).getTableCells();
            tableCells.get(0).setText("规则名称");
            tableCells.get(1).setText("校验字段");
            tableCells.get(2).setText("校验规则");
            tableCells.get(3).setText("实际结果");
            tableCells.get(4).setText("规则描述");
            List<XWPFTableCell> tableCellsVarT = table.getRow(1).getTableCells();
            tableCellsVarT.get(0).setText(ruleDetailDTO.getRuleName());
            tableCellsVarT.get(1).setText(ruleDetailDTO.getFieldName());
            tableCellsVarT.get(2).setText(ruleDetailDTO.getRuleTemplate());
            tableCellsVarT.get(3).setText(ruleDetailDTO.getCheckStatus());
            tableCellsVarT.get(4).setText(ruleDetailDTO.getDesc());
        }
        return doc;
    }


    private static void createTitle(XWPFDocument doc, String content) {
        XWPFParagraph title = doc.createParagraph();
        title.setAlignment(ParagraphAlignment.CENTER);
        XWPFRun r1 = title.createRun();
        r1.setBold(true);
        r1.setFontFamily("宋体");
        r1.setText(content);
        r1.setFontSize(22);
    }

    private static void createChapterH1(XWPFDocument doc, String content) {
        XWPFParagraph actTheme = doc.createParagraph();
        actTheme.setAlignment(ParagraphAlignment.LEFT);
        XWPFRun runText1 = actTheme.createRun();
        runText1.setBold(true);
        runText1.setText(content);
        runText1.setFontSize(18);
    }

    private static void createChapterH2(XWPFDocument doc, String content) {
        XWPFParagraph actType = doc.createParagraph();
        XWPFRun runText2 = actType.createRun();
        runText2.setBold(true);
        runText2.setText(content);
        runText2.setFontSize(15);
    }

    private static void createParagraph(XWPFDocument doc, String content) {
        XWPFParagraph actType = doc.createParagraph();
        XWPFRun runText2 = actType.createRun();
        runText2.setText(content);
        runText2.setFontSize(11);
    }


}
